<template>
  <div>
    <div style="display: flex;justify-content: space-between;">
      <!-- 添加 -->
      <el-button type="primary" @click="showDialog">添加攻略</el-button>
      <!-- 搜索 -->
      <div style="display: flex;">
        <el-input v-model.trim="pathname" placeholder="请输入攻略名称"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch(pathname)">搜索</el-button>
      </div>
    </div>

    <!-- 列表信息 -->
    <el-table :data="showList" style="width: 100%;margin-top: 20px;" fit border>
      <el-table-column label="攻略名称" width="180" align="center">
        <template #default="scope">
          <span style="margin-left: 10px">{{ scope.row.title ? scope.row.title : '信息未上传' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" width="250" align="center">
        <template #default="scope">
          <div slot="reference" class="name-wrapper">
            <img v-if="scope.row.image != ''" :src="scope.row.image" class="img" alt="图片信息错误" />
            <p v-if="scope.row.image == ''">未上传图片</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="内容" width="400">
        <template #default="scope">
          <span style="margin-left: 10px">{{ scope.row.content ? scope.row.content : '信息未上传' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block">
      <el-pagination layout="prev, pager, next" :total=totalElements :page-size="pageSize" @current-change="onChange">
      </el-pagination>
    </div>

    <!-- 新建、修改攻略 -->
    <el-dialog title="新建攻略" :visible.sync="dialog" width="50%">
      <div class="method">
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="80px" class="demo-ruleForm">
          <el-form-item label="攻略名称" prop="title">
            <el-input type="input" v-model="ruleForm.title" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input type="textarea" v-model="ruleForm.content" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="图片" prop="image">
            <el-upload class="upload" action="http://localhost:3001/upload" :show-file-list="false" :auto-upload="false"
              :on-change="handleChange" accept=".gif,.jpg,.jpeg,.png,.GIF,.JPG,.bmp" name="img">
              <img v-if="this.ruleForm.image != ''" :src="this.ruleForm.image" class="upload-image">
              <i v-if="this.ruleForm.image == ''" class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <div class="btns">
              <el-button type="primary" size="mini" @click="uploadForm" v-show="!this.ruleForm.id">提交</el-button>
              <el-button type="primary" size="mini" @click="uploadEditForm" v-show="this.ruleForm.id">保存</el-button>
              <el-button size="mini" @click="dialog = false">取 消</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
export default {
  data() {
    var checkTitle = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('攻略名称不能为空'));
      }
      callback();
    };
    var checkContent = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('内容不能为空'));
      }
      callback();
    };
    return {
      totalElements: 0,//总条数
      pathList: [],//总列表
      showList: [],//分页显示列表
      pageSize: 10,//每页条数
      dialog: false,
      pathname: '',//搜索框的输入内容
      ruleForm: {
        id: '',
        title: '',//攻略名称
        content: '',//攻略内容
        image: '',
      },
      rules: {
        title: [
          { validator: checkTitle, trigger: 'blur', required: true }
        ],
        content: [
          { validator: checkContent, trigger: 'blur', required: true }
        ],
      },
      imageUrl: '',
    }
  },
  methods: {
    //修改攻略
    async uploadEditForm() {
      await this.$http.post("/editmethod", {
        id: this.ruleForm.id,
        title: this.ruleForm.title,
        content: this.ruleForm.content,
        image: this.ruleForm.image,
      }).then(res => {
        console.log(res);
        if (res.code == 200) {
          this.$message.success(res.status)
          this.dialog = false;
          console.log(this.pathname)
          if (this.pathname) {
            this.handleSearch(this.pathname)
          } else {
            this.getList()
          }
        }
      })
      this.ruleForm.image = '';
    },
    //添加攻略
    async uploadForm() {
      await this.$http.post("/submethod", {
        title: this.ruleForm.title,
        content: this.ruleForm.content,
        image: this.ruleForm.image,
      }).then(res => {
        console.log(res)
        if (res.code == 200) {
          this.$message.success(res.status)
          this.dialog = false;
          this.getList()
        }
      })
      console.log(this.ruleForm.image);
      this.ruleForm.image = '';
    },
    //展示dialog
    showDialog() {
      this.dialog = true;
      this.ruleForm.id = "";
      this.ruleForm.title = "";
      this.ruleForm.content = '';
      this.ruleForm.image = '';
    },
    //搜索
    async handleSearch(pathname) {
      await this.$http.post("/search", { title: pathname }).then(res => {
        if (res.code == 200) {
          let result = res.data;
          for (let i in result) {
            let header = result[i].image.split('/')[0]
            if (header == '..') {
              result[i].image = result[i].image.split('/')[4]
              result[i].image = require("../../../trip-koa/public/methodimg/" + result[i].image)
            }
          }
          this.pathList = result;
          this.totalElements = this.pathList.length;
          if (this.totalElements <= this.pageSize) {
            this.showList = this.pathList
          } else {
            this.showList = this.pathList.slice(0, this.pageSize)
          }
        } else {
          this.$message.error(res.status)
        }
      })
    },
    //编辑攻略
    handleEdit(index, row) {
      this.dialog = true;
      this.ruleForm.id = row.id;
      this.ruleForm.title = row.title;
      this.ruleForm.content = row.content;
      this.ruleForm.image = row.image;
    },
    //删除攻略
    async handleDelete(index, row) {
      let id = row.id;
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.post("/delmethod", { id: id }).then(res => {
          if (res.code == 200) {
            this.pathList.splice(index, 1);
            this.$message.success(res.status)
            if (this.pathname) {
              this.handleSearch(this.pathname)
            } else {
              this.getList()
            }
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      });
    },

    //上传图片
    blobToBase64(blob) {
      return new Promise((resolve, reject) => {
        const fileReader = new FileReader();
        fileReader.onload = (e) => {
          resolve(e.target.result)
        }
        fileReader.readAsDataURL(blob)
        fileReader.onerror = () => {
          reject(new Error("文件流异常"))
        }
      })
    },
    handleChange(file, fileList) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.blobToBase64(file.raw).then(res => {
        this.ruleForm.image = res
      })
    },

    //分页
    onChange(pageNumber) {
      this.showList = [];
      if (this.totalElements < pageNumber * this.pageSize) {
        this.showList = this.pathList.slice(this.pageSize * (pageNumber - 1))
      } else {
        this.showList = this.pathList.slice(this.pageSize * (pageNumber - 1), this.pageSize * pageNumber)
      }
    },
    //获取列表数据
    async getList() {
      await this.$http.get("/getmethod").then(res => {
        let result = res.data;
        for (let i in result) {
          let header = result[i].image.split('/')[0]
          if (header == '..') {
            result[i].image = result[i].image.split('/')[4]
            result[i].image = require("../../../trip-koa/public/methodimg/" + result[i].image)
          }
        }
        this.pathList = result;
        this.totalElements = this.pathList.length;
        if (this.totalElements <= this.pageSize) {
          this.showList = this.pathList
        } else {
          this.showList = this.pathList.slice(0, this.pageSize)
        }
      })
    },
  },

  mounted() {
    this.getList();
  },
}
</script>

<style>
.img {
  width: 180px;
}

.method {
  width: 80%;
  margin: 0 auto;
}

.btns {
  width: 35%;
  margin: 0 auto;
}

.upload .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 5px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.upload .upload:hover {
  border-color: #409EFF;
}

.el-icon-plus {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  /* text-align: center; */
}

.upload-image {
  width: 150px;
  height: 150px;
  display: block;
}
</style>